package admin.service.impl;

import admin.entity.Token;
import admin.entity.User;
import admin.mapper.TokenMapper;
import admin.mapper.UserMapper;
import admin.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author xf07b1
 * @wechat xf07b1
 * @description
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final TokenMapper tokenMapper;

    @Override
    public void page(Page<User> page, User user) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
                .eq(!ObjectUtils.isEmpty(user.getId()), User::getId, user.getId())
                .eq(!ObjectUtils.isEmpty(user.getUsername()), User::getUsername, user.getUsername())
                .like(!ObjectUtils.isEmpty(user.getName()), User::getName, user.getName());
        this.page(page, wrapper);
    }

    @Override
    public boolean exist(String username) {
        return baseMapper.exists(Wrappers.lambdaQuery(User.class).eq(User::getUsername, username));
    }

    @Override
    public String login(String username, String password) {
        User user = baseMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, username)
                .eq(User::getPassword, password));

        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        boolean exists = tokenMapper.exists(Wrappers.lambdaQuery(Token.class).eq(Token::getUserId, user.getId()));

        Token token = new Token();
        token.setUserId(user.getId());
        token.setValue(UUID.randomUUID().toString());
        token.setExpiration(LocalDateTime.now().plusDays(1));
        if (exists) {
            tokenMapper.updateById(token);
        } else {
            tokenMapper.insert(token);
        }

        return token.getValue();
    }

    @Override
    public User getByUsername(String username) {
        return baseMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, username));
    }
}
